import router from './router'
import store from './store'
import {hasPermission} from './utils/sift';

const whiteList = ['/login', 'error']

router.beforeEach((to, from, next) => {
	if (store.getters.store_token) {
		store.dispatch('isLogin', store.getters.store_token).then(res => {
			if (res.data.code === 0) {
				if (to.path === '/login') {
					next({
						path: '/'
					})
				} else {
					if (store.getters.store_phone === '') {
						store.dispatch('GetUserInfo').then(res => {
							const permissions = res.permissions;
							store.dispatch('FormatRoutes', permissions).then(() => {
								router.addRoutes(store.getters.store_add_routers);
								next(to.path);
							});
						}).catch(()=>{
							store.dispatch("Logout");
						})
					} else {
						if (hasPermission(store.getters.store_permissions, to)) {
							next();
						} else {
							next({
								path: '/403'
							});
						}
					}
				}
			} else {
				store.dispatch('Logout', store.getters.store_token).then(() => {
					next('/login')
				})

			}
		}).catch(() => {
			store.dispatch('Logout', store.getters.store_token).then(() => {
				next('/login')
			})
		})
	} else {
		if (whiteList.indexOf(to.path) !== -1) {
			next();
		} else {
			next('/login');
		}
	}
})
